﻿// 2023/3/20: 首个版本
// 2024/1/29: 增加查看详情按钮（仅通过BoolResult输出是否请求查看）
// 2024/6/25: 支持API3，支持异步
// 2024/10/23: 使用新回调接口
// 2025/8/25: 支持暗色模式

using System;
using ASEva;
using ASEva.UIEto;
using Eto.Forms;
using Eto.Drawing;
using System.Threading.Tasks;

namespace CommonSource
{
    class TaskBanner : DialogPanel
    {
        public TaskBanner(String title, bool withCheckDetails = false)
        {
            Title = title;
            SetFixMode(700, 75, false);

            var mainLayout = this.SetContentAsColumnLayout();
            mainLayout.BackgroundColor = Colors.LightSteelBlue;

            var titleLayout = mainLayout.AddRowLayout(true);
            progressBar = mainLayout.AddControl(new ProgressBar{ MaxValue = 1000 }, true) as ProgressBar;
            var stateLayout = mainLayout.AddRowLayout(true);

            titleLayout.AddLabel(chinese ? "当前任务：" : "Current task:");
            titleLayout.AddLabel(title, true);
            labelPercent = titleLayout.AddLabel("0.0%");

            labelState = stateLayout.AddLabel("", true);
            if (withCheckDetails) checkDetails = stateLayout.AddCheckBox(chinese ? "查看详情" : "Check details");
            linkCancel = stateLayout.AddLinkButton(chinese ? "取消" : "Cancel");

            linkCancel.Click += delegate
            {
                linkCancel.Enabled = false;
                callback.CancelTask();
            };

            if (checkDetails != null)
            {
                checkDetails.CheckedChanged += delegate
                {
                    BoolResult = checkDetails.Checked.Value;
                };
            }
        }

        public async Task RunTask(WorkflowRunTaskCallback callback)
        {
            if (running) return;
            else running = true;

            this.callback = callback;
            
            loopTimer = new UITimer();
            loopTimer.Interval = 0.1;
            loopTimer.Elapsed += delegate
            {
                if (looping) return;
                looping = true;

                var state = callback.GetTaskState();
                var description = callback.GetTaskStateDescription();
                var progress = callback.GetTaskProgress();

                if (description == null) description = "";

                switch (state)
                {
                    case TaskState.Unknown:
                        labelPercent.TextColor = Colors.Gray;
                        break;
                    case TaskState.Progressing:
                        labelPercent.TextColor = App.DarkTheme ? Colors.White : Colors.Black;
                        break;
                    case TaskState.Failed:
                        labelPercent.TextColor = Colors.Red;
                        break;
                    case TaskState.Finished:
                        labelPercent.TextColor = Colors.Green;
                        break;
                }

                labelState.Text = description;

                progress = Math.Max(0.0, Math.Min(100.0, progress));
                progressBar.Value = (int)(progress * 10);
                labelPercent.Text = progress.ToString("F1") + "%";

                if (state == TaskState.Failed || state == TaskState.Finished)
                {
                    linkCancel.Enabled = false;
                    loopTimer.Stop();
                    loopTimer = null;

                    closeTimer = new UITimer();
                    closeTimer.Interval = 2;
                    closeTimer.Elapsed += delegate
                    {
                        closeTimer.Stop();
                        closeTimer = null;
                        Close();
                    };
                    closeTimer.Start();
                }

                looping = false;
            };
            loopTimer.Start();

            await App.RunDialog(this);
        }

        private WorkflowRunTaskCallback callback;
        private Label labelPercent, labelState;
        private ProgressBar progressBar;
        private LinkButton linkCancel;
        private CheckBox checkDetails;
        private UITimer loopTimer, closeTimer;
        private bool running = false;
        private bool looping = false;
        private bool chinese = AgencyLocal.GetAppLanguage() == Language.Chinese;
    }
}